package com.cskaoyan.market.admin.controller;

import com.cskaoyan.market.admin.bo.GoodsCombineBo;
import com.cskaoyan.market.admin.bo.GoodsDetailBo;
import com.cskaoyan.market.admin.service.MarketGoodsService;
import com.cskaoyan.market.db.domain.MarketGoods;
import com.cskaoyan.market.db.domain.MarketGoodsSpecification;
import com.cskaoyan.market.util.HttpUtil;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
    *@Author：檀志浩
    *@Package：com.cskaoyan.market.controller
    *@Project：Project1
    *@name：AdminGoodsController
    *@Date：2023/5/8  8:50
    *@Filename：AdminGoodsController
    */
@RestController
@RequestMapping("/admin/goods")
public class AdminGoodsController {
    @Autowired
    MarketGoodsService goodsService;

    @PostMapping("/create")
    private void create(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //先获取请求参数----请求参数位于请求体，并且是json字符串
        //首先获取请求体，这部分代码我们写过，复用
        String requestBody = HttpUtil.parseRequestBody(req);
        //需要将json字符串转换成java对象
        ObjectMapper objectMapper = JacksonUtil.getObjectMapper();
        GoodsCombineBo combineBo = objectMapper.readValue(requestBody, GoodsCombineBo.class);
        //校验---商品的名称不能为空，规格名称不能为空，
        boolean result = valid(combineBo);
        if(!result){
            //校验没有通过
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
            return;
        }
        goodsService.addGoods(combineBo.getGoods(), combineBo.getSpecifications(), combineBo.getAttributes(), combineBo.getProducts());
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.ok()));
    }

    private boolean valid(GoodsCombineBo combineBo) {
        MarketGoods goods = combineBo.getGoods();
        List<MarketGoodsSpecification> specifications = combineBo.getSpecifications();
        if(StringUtils.isEmpty(goods.getName())){
            return false;
        }
        for (MarketGoodsSpecification specification : specifications) {
            if(StringUtils.isEmpty(specification.getSpecification())){
                return false;
            }
            if(StringUtils.isEmpty(specification.getValue())){
                return false;
            }
        }
        return true;
    }

    @PostMapping("/update")
    private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = HttpUtil.parseRequestBody(req);
        GoodsCombineBo goodsCombineBo = JacksonUtil.getObjectMapper().readValue(requestBody,
                GoodsCombineBo.class);

        int resCode = goodsService.update(goodsCombineBo);
        String resultString;
        if (resCode == 1) {
            resultString = JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.ok());
        } else {
            resultString = JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.fail(-1, "商品修改失败"));
        }
        // 返回响应体
        resp.getWriter().println(resultString);
    }

    @PostMapping("/delete")
    private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = HttpUtil.parseRequestBody(req);
        MarketGoods marketGoods = JacksonUtil.getObjectMapper().readValue(requestBody, MarketGoods.class);
        if (marketGoods.getId()==null){
            Object bad = ResponseUtil.badArgumentValue();
            resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(bad));
            return;
        }
        int delete = goodsService.delete(marketGoods);
        if (delete==-1){
            Object fail = ResponseUtil.fail();
            resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(fail));
            return;
        }
        if (delete==1){
            Object ok = ResponseUtil.ok();
            resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ok));
        }
    }
    

    @GetMapping("/detail")
    private void detail(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String idStr = req.getParameter("id");
                if (StringUtils.isEmpty(idStr)) {
            resp.getWriter().println(ResponseUtil.badArgumentValue());
            return;
        }
        Integer id = null;
        try {
            id = Integer.parseInt(idStr);
        } catch (Exception e) {
            resp.getWriter().println(ResponseUtil.badArgumentValue());
            return;
        }
        GoodsDetailBo detail = goodsService.detail(id);
        HashMap<String, Object> detailMap = new HashMap<>();
        detailMap.put("categoryIds", detail.getCategoryIds());
        detailMap.put("goods", detail.getGoods());
        detailMap.put("attributes", detail.getAttributes());
        detailMap.put("specifications", detail.getSpecifications());
        detailMap.put("products", detail.getProducts());
        Object ok = ResponseUtil.ok(detailMap);
        resp.getWriter().println(JacksonUtil.writeValueAsString(ok));
    }


    @GetMapping("/list")
    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //1.获取接收请求参数
        //因为我们涉及到分页，所以这里面必须要有当前页，以及每页的数量，如果传递过来的不是数字，没有考虑到这一点那么可能会出错
        //针对上述这个要求，我们可以有两种就解决方案：
        //1.强制进行校验，如果不符合要求，直接返回一个错误状态码回去
        //2.不做校验，如果不合法，那么我给它赋值一个默认值1,20
        String pageParam = req.getParameter("page");
        String limitParam = req.getParameter("limit");
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");
        String goodsId = req.getParameter("goodsId");
        String goodsSn = req.getParameter("goodsSn");
        String name = req.getParameter("name");
        if(StringUtils.isEmpty(sort)){
            sort = "add_time";
        }
        if(StringUtils.isEmpty(order)){
            order = "desc";
        }
        Integer page = null;
        Integer limit = null;
        try {
            //做校验，保证page和limit必须存在，且是数字
            page = Integer.parseInt(pageParam);
            limit =Integer.parseInt(limitParam);
        }catch (Exception e){
            resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.badArgument()));
            return;
        }
        // Object ok = ResponseUtil.okList(goodsList);
        // String s = JacksonUtil.getObjectMapper().writeValueAsString(ok);
        // resp.getWriter().println(s);
        List<MarketGoods> marketGoodsList = goodsService.list(page,limit,goodsSn,sort,order,goodsId,name);
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.okList(marketGoodsList)));

    }

    @GetMapping("/catAndBrand")
    private void catAndBrand(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Map<String, Object> result = goodsService.catAndBrand();
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.ok(result)));
    }
}
